package com.cy.stone.framework.systemdict;

import cn.hutool.core.collection.CollUtil;
import com.cy.stone.common.constant.Constant;
import com.cy.stone.system.infrastructure.database.entity.DictDataEntity;
import com.cy.stone.system.infrastructure.database.entity.DictTypeEntity;
import com.cy.stone.system.infrastructure.database.service.IDictDataService;
import com.cy.stone.system.infrastructure.database.service.IDictTypeService;
import com.houkunlin.system.dict.starter.bean.DictTypeVo;
import com.houkunlin.system.dict.starter.provider.DictProvider;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.cy.stone.system.infrastructure.database.table.DictDataTableDef.DICT_DATA_ENTITY;
import static com.cy.stone.system.infrastructure.database.table.DictTypeTableDef.DICT_TYPE_ENTITY;

/**
 * 字典数据获取并缓存
 * @author Wings
 * @since 2023-12-17
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class DictDataProvider implements DictProvider {

    private final IDictTypeService dictTypeService;

    private final IDictDataService dictDataService;

    @Override
    public boolean isStoreDictType() {
        return true;
    }

    @Override
    public Iterator<DictTypeVo> dictTypeIterator() {
        log.info("======数据字典缓存开始======");
        List<DictTypeEntity> types = dictTypeService.list(QueryWrapper.create()
                .from(DICT_TYPE_ENTITY)
                .where(DICT_TYPE_ENTITY.STATUS.eq(Constant.STATUS_0)));
        List<DictTypeVo> vos = new ArrayList<>();
        for(DictTypeEntity type : types) {
            DictTypeVo.DictTypeBuilder builder = DictTypeVo.newBuilder(type.getDictType(), type.getDictName());
            List<DictDataEntity> dicts = dictDataService.list(QueryWrapper.create()
                    .from(DICT_DATA_ENTITY)
                    .where(DICT_DATA_ENTITY.DICT_TYPE.eq(type.getDictType()))
                    .and(DICT_DATA_ENTITY.STATUS.eq(Constant.STATUS_0)));
            if(CollUtil.isNotEmpty(dicts)) {
                for(DictDataEntity dict : dicts) {
                    builder.add(dict.getDictCode(), dict.getDictValue());
                }
            }
            final DictTypeVo dictTypeVo = builder.build();
            vos.add(dictTypeVo);
        }
        log.info("======数据字典缓存结束======");
        return vos.iterator();
    }
}
